//
//  OutputView.m
//  OutputView
//
//  Created by 杨海波 on 2017/3/15.
//  Copyright © 2017年 杨海波. All rights reserved.
//

#import "OutputView.h"
/****************************适配*********************************/
#define Width [UIScreen mainScreen].bounds.size.width
#define Height [UIScreen mainScreen].bounds.size.height
#define ratew (Width/375.0)
#define rateh (Height/667.0)
#define CGRect(x,y,width,heigth)  CGRectMake((x)*ratew, (y)*rateh, width*ratew, heigth*rateh)
#define RGB(r,g,b)  [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]
/****************************适配*********************************/
#define textSize  18*rateh//字体大小

@implementation OutputView
{
    CGPoint _origin;
    CGFloat _rowHeigth;//cell的高
    CGFloat _rowWidth;//cell的宽
    Direction _direction;//箭头方向设置
    CGFloat  _arrow_x;//箭头偏移量
    UIColor *_separatorColor;//下划线颜色
}

-(instancetype)initWithPoint:(CGPoint)origin rowHeigth:(CGFloat)rowHeigth direction:(Direction)direction dataArray:(NSArray*)dataArray{
    self = [super initWithFrame:CGRectMake(0, 0, Width, Height)];
    if (self) {
        self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"color_alph"]];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, Height)];
        view.backgroundColor = [UIColor clearColor];
        [self addSubview:view];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapEvent:)];
        [view addGestureRecognizer:tap];
        
        _origin = origin;
        _rowHeigth = rowHeigth;
        _direction = direction;
        _dataArray = dataArray;
        _textAlignment = NSTextAlignmentCenter;
        _separatorColor = RGB(220, 220, 220);
        
        for (id obj in _dataArray) {
            NSString *name = @"";
            if ([obj isKindOfClass:[NSString class]]) {
                name = obj;
            }else if ([obj isKindOfClass:[NSDictionary class]]){
                name = obj[@"title"];
            }
            if (name.length==0) {
                name = obj[@"name"];
            }
            NSDictionary *fontDic=@{NSFontAttributeName:[UIFont systemFontOfSize:textSize]};
            CGSize titleLabelSize=[name boundingRectWithSize:CGSizeMake(Width-20, 20) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading|NSStringDrawingUsesDeviceMetrics  attributes:fontDic context:nil].size;
            CGFloat row = titleLabelSize.width+50;
            if (_rowWidth<row) {
                _rowWidth = row;
            }
        }
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectNull style:UITableViewStylePlain];
        _tableView.separatorColor = [UIColor colorWithWhite:0.3 alpha:1];
        _tableView.backgroundColor = [UIColor colorWithWhite:0.2 alpha:1];
        _tableView.bounces = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.layer.cornerRadius = 5;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self setTableViewRect];//设置tableview大小
        [self addSubview:self.tableView];
        //cell线条
        if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
            [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        }
        if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
            [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        }
    }
    return self;
}
//设置tableview大小
-(void)setTableViewRect{
    CGRect rect;
    CGFloat tableview_height = _rowHeigth * _dataArray.count;
    if (tableview_height>Height/2) {
        _tableView.bounces = YES;
        tableview_height = Height/2;
    }
    
    if (_direction == OutputViewDirectionLeft) {
        rect = CGRectMake(_origin.x, _origin.y, _rowWidth, tableview_height);
    }else if (_direction == OutputViewDirectionCenter) {
        rect = CGRectMake(_origin.x-_rowWidth/2, _origin.y, _rowWidth, tableview_height);
    }else if (_direction == OutputViewDirectionRight) {
        rect = CGRectMake(_origin.x-_rowWidth, _origin.y, _rowWidth, tableview_height);
    }else if(_direction == OutputViewDirectionDownLeft){
        rect = CGRectMake(_origin.x, _origin.y-_rowHeigth * _dataArray.count, _rowWidth, tableview_height);
    }else if(_direction == OutputViewDirectionDownCenter){
        rect = CGRectMake(_origin.x-_rowWidth/2, _origin.y-_rowHeigth * _dataArray.count, _rowWidth, tableview_height);
    }else if(_direction == OutputViewDirectionDownRight){
        rect = CGRectMake(_origin.x-_rowWidth, _origin.y-_rowHeigth * _dataArray.count, _rowWidth, tableview_height);
    }else{
        rect = CGRectMake(_origin.x, _origin.y, _rowWidth, tableview_height);
    }
    self.tableView.frame = rect;
}
//设置弹框宽度
-(void)setRowWidth:(CGFloat)rowWidth{
    _rowWidth = rowWidth;
    [self setTableViewRect];
}
//设置箭头左右偏移量
-(void)setArrow_x:(CGFloat)arrow_x{
    _arrow_x = arrow_x;
    [self setNeedsDisplayInRect:self.frame];
}
//设置分割线颜色
-(void)setSeparatorColor:(UIColor*)separatorColor{
    _separatorColor = separatorColor;
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return _rowHeigth;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        if (indexPath.row!=_dataArray.count-1) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, _rowHeigth-0.5, Width, 0.5)];
            line.backgroundColor = _separatorColor;
            [cell addSubview:line];
        }
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textAlignment = _textAlignment;
    cell.textLabel.font = [UIFont systemFontOfSize:textSize];
    if (_celltextColor) {
        cell.textLabel.textColor = _celltextColor;
    }else{
        cell.textLabel.textColor = [UIColor whiteColor];
    }
    //取出模型
    id info = _dataArray[indexPath.row];
    if ([info isKindOfClass:[NSString class]]) {
        cell.textLabel.text = info;
    }else if ([info isKindOfClass:[NSDictionary class]]){
        if (info[@"title"]==nil) {
            cell.textLabel.text = info[@"name"];
        }else{
            cell.textLabel.text = info[@"title"];
        }
        if ([info[@"img"] length]>0) {
            cell.imageView.image = [UIImage imageNamed:info[@"img"]];
        }else{
            cell.imageView.image = [UIImage imageNamed:@""];
        }
    }
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = tableView.backgroundColor;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //通知代理处理点击事件
    if (_delegate) {
        [_delegate didSelectedAtIndexPath:indexPath];
    }
    if (_resultBlock) {
        NSString *row = [NSString stringWithFormat:@"%d",(int)indexPath.row];
        _resultBlock(row);
    }
    [self dismiss];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}
//弹出
- (void)pop{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:self];
    CGRect frame = _tableView.frame;
    self.alpha = 0;
    _tableView.frame = [self getRectWhileDismiss];//获取消失状态的位置信息
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 1;
        _tableView.frame = frame;
    }];
}
//弹出两次动画
- (void)popForTwo{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:self];
    CGRect frame = _tableView.frame;
    _tableView.frame = [self getRectWhileDismiss];//获取消失状态的位置信息
    if (_direction == OutputViewDirectionLeft||_direction == OutputViewDirectionCenter||_direction == OutputViewDirectionRight) {
        _tableView.layer.anchorPoint = CGPointMake(0.5, 0);
    }else{
        _tableView.layer.anchorPoint = CGPointMake(0.5, 1);
    }
    self.alpha = 0;
    [UIView animateKeyframesWithDuration:0.25 delay:0 options:0 animations: ^{
        self.alpha = 1;
        _tableView.frame = frame;
        _tableView.transform = CGAffineTransformMakeScale(1.06, 1.06);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            _tableView.transform = CGAffineTransformMakeScale(1.0, 1.0);
        }];
    }];
}


//视图消失
- (void)dismiss {
    self.alpha = 1;
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 0;
        _tableView.frame = [self getRectWhileDismiss];//获取消失状态的位置信息
        if (_dismissBlock) {
            _dismissBlock(@"dismiss");//消失
        }
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeFromSuperview];
        }
    }];
}
//获取消失时的frame
-(CGRect)getRectWhileDismiss{
    CGRect frame = _tableView.frame;
    CGRect rect;
    if (_direction==OutputViewDirectionCenter) {
        rect = CGRectMake(frame.origin.x, frame.origin.y, _rowWidth, 0);
    }else if (_direction==OutputViewDirectionLeft){
        rect = CGRectMake(frame.origin.x, frame.origin.y, 0, 0);
    }else if (_direction==OutputViewDirectionRight) {
        rect = CGRectMake(frame.origin.x+frame.size.width, frame.origin.y, 0, 0);
    }else if (_direction==OutputViewDirectionDownCenter) {
        rect = CGRectMake(frame.origin.x, frame.origin.y+frame.size.height, _rowWidth, 0);
    }else if (_direction==OutputViewDirectionDownLeft) {
        rect = CGRectMake(frame.origin.x, frame.origin.y+frame.size.height, 0, 0);
    }else {//_direction==OutputViewDirectionDownRight
        rect = CGRectMake(frame.origin.x+frame.size.width, frame.origin.y+frame.size.height, 0, 0);
    }
    return rect;
}
-(void)tapEvent:(UITapGestureRecognizer*)tap{
    [self dismiss];
}

//绘制三角形
-(void)drawRect:(CGRect)rect{
    //获取画板
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);
    
    CGFloat startX;
    CGFloat startY;
    CGFloat sign = 1.0;//符号
    //箭头朝上
    if (_direction==OutputViewDirectionLeft) {
        startX = _origin.x + 10+_arrow_x;
        startY = _origin.y;
    }else if (_direction==OutputViewDirectionRight) {
        startX = _origin.x - 20-_arrow_x;
        startY = _origin.y;
    }else if(_direction==OutputViewDirectionCenter){
        startX = _origin.x-5-_arrow_x;
        startY = _origin.y;
    }
    //箭头朝下
    else if(_direction==OutputViewDirectionDownLeft){
        startX = _origin.x + 10+_arrow_x;
        startY = _origin.y;
        sign = -1.0;
    }else if(_direction==OutputViewDirectionDownRight){
        startX = _origin.x -20-_arrow_x ;
        startY = _origin.y;
        sign = -1.0;
    }else {//_direction==OutputViewDirectionDownCenter
        startX = _origin.x-5-_arrow_x;
        startY = _origin.y;
        sign = -1.0;
    }
    
    CGContextMoveToPoint(context, startX, startY);//设置起点
    CGContextAddLineToPoint(context, startX+5, startY-5*sign);
    CGContextAddLineToPoint(context, startX+10, startY);
    
    CGContextClosePath(context);
    [_tableView.backgroundColor setFill];
    [_tableView.backgroundColor setStroke];
    CGContextDrawPath(context, kCGPathFillStroke);
}






@end







